import { pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2, previewer } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import './index.scss';
import { ChildLineCommandProps } from './types';

type FormDataItem = {
  point?: pickedVertexData;
  radius: number;
};

type FormData = FormDataItem[];

export const Polyline = ({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) => {
  const [isLoading, setIsLoading] = useState(false);

  const defaultForm = [
    { point: undefined, radius: 0 },
    { point: undefined, radius: 0 },
    { point: undefined, radius: 0 },
  ];
  const [formData, setFormData] = useState<FormData>(defaultForm);
  const { picker } = useTools();

  const init = async () => {
    if (props == null) {
      return;
    }

    const propsPoints = props.params.points;
    for (const item of propsPoints) {
      await initEditDependency([item.point]);
    }
    const formData: FormData = propsPoints.map((item) => {
      return {
        point: picker.generatePickObjByPickID(item.point) as pickedVertexData,
        radius: item.radius,
      };
    });
    formData.push({ point: undefined, radius: 0 });
    setFormData(formData);
  };

  useAsyncEffect(init, [editDxid]);

  const nonNullItems = formData.filter((p) => p?.point != null);

  const isFormDataValid = () => {
    return (
      nonNullItems.length > 2 &&
      formData.slice(0, -1).every((p) => p?.point != null)
    );
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    setIsLoading(true);
    const params = formData
      .filter((item) => item.point)
      .map((item) => ({ point: item.point.vertexId, radius: item.radius }));
    try {
      if (editDxid == null) {
        await wsApi.createPolyline(params);
      } else {
        await wsApi.setParams(editDxid, {
          type: 'Polygon',
          points: params,
        });
      }
    } finally {
      setIsLoading(false);
    }

    onClose();
  };

  const { initEditDependency, initingEdit, previewInCommand } = useCommand(
    'cmd-line-between-dot',
    {
      onClose,
      finishDraw: checkAndFinishDraw,
    },
  );

  const preview = () => {
    if (isFormDataValid()) {
      const params = formData
        .filter((item) => item.point)
        .map((item) => ({ point: item.point.vertexId, radius: item.radius }));
      wsApi.createPolyline(params, true).then((res) => {
        previewInCommand(res);
      });
    } else {
      previewer.clear();
    }

    ctx2.viewer.requestRender();
  };

  useEffect(preview, [formData]);

  const schema: RJSFSchema = {
    type: 'array',
    items: {
      type: 'object',
      title: '通过点',
      properties: {
        point: {
          type: 'string',
          title: '点',
          format: PickInputRJSFFormat.PickVertex,
        },
        radius: {
          type: 'number',
          title: '半径',
          format: NumberInputFormat.Length,
        },
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      submitLoading={isLoading}
      schema={schema}
      onCancel={onClose}
      formData={formData}
      onChange={(v: FormData) => {
        const firstNonNullItem = v.find((item) => item.point != null);
        const lastNonNullItem = v.findLast((item) => item.point != null);

        const edgeHasRadius =
          firstNonNullItem &&
          (firstNonNullItem.radius !== 0 ||
            // lastNonNullItem is guaranteed if firstNonNullItem exists
            lastNonNullItem.radius !== 0);

        if (edgeHasRadius) {
          MessageTip.warning('首尾点不可设置半径参数。');

          firstNonNullItem.radius = 0;
          lastNonNullItem.radius = 0;
        }

        const newFormData = [...v];
        if (newFormData.at(-1)?.point != null) {
          newFormData.push({ point: undefined, radius: 0 });
        }

        setFormData(newFormData);
      }}
      extraUiSchema={{
        'ui:options': {
          classNames:
            'command-form command-form-array command-form_cmd-polyline',
        },
        items: {
          point: {
            'ui:placeholder': '请输入点',
            'ui:autofocus': true,
            'ui:options': {
              classNames: 'command-form_cmd-cad-point',
            },
          },
          radius: { 'ui:placeholder': '请输入半径' },
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
